package com.douqu.game.main.msg;


import com.alibaba.fastjson.JSONObject;
import com.bean.core.util.HttpJsonUtils;
import com.douqu.game.core.config.StableDataConfig;
import com.douqu.game.core.config.common.GoodsData;
import com.douqu.game.core.controller.PlayerController;
import com.douqu.game.core.e.E_ActivityCampStatus;
import com.douqu.game.core.e.E_ApplyCampActivityType;
import com.douqu.game.core.e.E_StableDataType;
import com.douqu.game.core.e.ReturnMessage;
import com.douqu.game.core.entity.activity.RankCamp;
import com.douqu.game.core.entity.battle.BattleTemp;
import com.douqu.game.core.entity.battle.SpriteTemp;
import com.douqu.game.core.entity.db.CardDB;
import com.douqu.game.core.entity.ext.BagInfo;
import com.douqu.game.core.entity.ext.data.challenge.CampBattleBean;
import com.douqu.game.core.entity.ext.data.challenge.CampBattleData;
import com.douqu.game.core.factory.ConfigFactory;
import com.douqu.game.core.factory.DataFactory;
import com.douqu.game.core.factory.WordFactory;
import com.douqu.game.core.protobuf.SGChallengeProto;
import com.douqu.game.core.protobuf.SGCommonProto;
import com.douqu.game.core.protobuf.SGMainProto;
import com.douqu.game.core.util.LogUtils;
import com.douqu.game.main.GameServer;
import com.douqu.game.main.server.ActivityCampManager;
import com.douqu.game.main.server.ServerManager;
import com.douqu.game.main.server.entity.ServerInfo;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author: Gavin.
 * Description:
 * Date: 2017/12/11 0011 下午 2:41
 * Huan Yu Copyright (c) 2017 All Rights Reserved.
 */
@Component
public class ActivityMsgChannel implements AMsgChannel  {




    @Override
    public void messageChannel(int code, PlayerController playerController, byte[] data) throws Exception
    {
        if(playerController == null)
            throw new Exception("playerController is null");

        switch (code) {
            /***********************阵营战***********************************************************/
            case SGMainProto.E_MSG_ID.MsgID_Activity_CampInit_VALUE:
                campInit(playerController, code);
                break;
            case SGMainProto.E_MSG_ID.MsgID_Activity_CampApply_VALUE://报名
                applyCampActivity(playerController);
                break;
            case SGMainProto.E_MSG_ID.MsgID_Activity_CampBattleRecord_VALUE://查看自己的比赛记录
                battleRecord(playerController, code);
                break;
            case SGMainProto.E_MSG_ID.MsgID_Activity_CampGetReward_VALUE://领取奖励
                getReward(playerController, code);
                break;
            case SGMainProto.E_MSG_ID.MsgID_Activity_CampArmyDetail_VALUE://军团详情
                armyDetail(playerController, code);
                break;
            case SGMainProto.E_MSG_ID.MsgID_Activity_CampMyInfo_VALUE:
                myInfo(playerController, code);
                break;
            default:
                break;
        }
    }

    private void myInfo(PlayerController playerController, int code)
    {
        SGChallengeProto.S2C_CampMyInfo.Builder response = SGChallengeProto.S2C_CampMyInfo.newBuilder();

        CampBattleData campBattleData = playerController.getPlayer().getCampBattleData();
        if(ActivityCampManager.getInstance().getStatus() != E_ActivityCampStatus.RUN_ING)
            response.setIsGetReward(!campBattleData.isGetRewarded() && campBattleData.curTotalExploit > 0);
        else
            response.setIsGetReward(false);

        response.setMyMaxRank(campBattleData.maxRank);
        int myCampRank = ActivityCampManager.getInstance().getCampRank(playerController.getPlayer().camp);
        response.setMyCampRank(myCampRank);
        response.setMyRank(ActivityCampManager.getInstance().getMyRank(playerController.getObjectIndex()));
        response.setMyMaxContinueWin(campBattleData.curMaxContinueWin);

        int initExploit = campBattleData.curTotalExploit;
        int addExploit = (int) (campBattleData.curMaxContinueWin * (initExploit * 0.05));
        addExploit = addExploit > initExploit ? initExploit : addExploit;
        response.setContinueWinReward(addExploit+"");

        if(myCampRank == 1)
//            response.setRankReward(initExploit + "*100%=" + initExploit);
            response.setRankReward(initExploit+"");
        else if(myCampRank == 2)
//            response.setRankReward(initExploit + "*60%=" + (initExploit*0.6));
            response.setRankReward((int)(initExploit*0.6)+"");
        else if(myCampRank == 3)
//            response.setRankReward(initExploit + "*40%=" + (initExploit*0.4));
            response.setRankReward((int)(initExploit*0.4)+"");

        playerController.sendMsg(code, response.build().toByteArray());
    }

    private void armyDetail(PlayerController playerController, int code)
    {
        SGChallengeProto.S2C_CampArmyDetail.Builder response = SGChallengeProto.S2C_CampArmyDetail.newBuilder();

        BattleTemp battleTemp = GameServer.getInstance().getWorldManager().getSpriteBattleTemp(SGCommonProto.E_BATTLE_TYPE.BATTLE_TYPE_SPAN_CAMP_VALUE, playerController.getObjectIndex());
        if(battleTemp != null)
        {
            for(SpriteTemp spriteTemp : battleTemp.getSoldierList())
            {
                response.addSoldier(SGCommonProto.CommonObject.newBuilder().setId(spriteTemp.getId()).setValue(spriteTemp.getHPRate()));
            }
        }
        else
        {
            for(CardDB cardDB : playerController.getPlayer().getCampCardList())
            {
                response.addSoldier(SGCommonProto.CommonObject.newBuilder().setId(cardDB.id).setValue(100));
            }
        }

        playerController.sendMsg(code, response.build().toByteArray());
    }

    private void getReward(PlayerController playerController, int code)
    {
        if(ActivityCampManager.getInstance().getStatus() == E_ActivityCampStatus.CLEAR_ING)
        {
            LogUtils.debug("正在结算中，请稍候再试");
            playerController.sendWarn(WordFactory.ACTIVITY_CAMP_CLEAR_ING);
            return;
        }

        if(ActivityCampManager.getInstance().getStatus() == E_ActivityCampStatus.RUN_ING)
        {
            LogUtils.debug("活动还没结束,不能领取奖励");
            playerController.sendWarn(WordFactory.ACTIVITY_CAMP_RUN_ING);
            return;
        }

        CampBattleData campBattleData = playerController.getPlayer().getCampBattleData();
        if(campBattleData.isGetRewarded())
        {
            LogUtils.debug("奖励已领取");
            playerController.sendWarn(WordFactory.ACTIVITY_CAMP_GET_REWARD_ED);
            return;
        }

        int myCampRank = ActivityCampManager.getInstance().getCampRank(playerController.getPlayer().camp);
        if(myCampRank == 0)
        {
            LogUtils.debug("还没有数据");
            playerController.sendWarn(WordFactory.ACTIVITY_CAMP_NO_REWARD);
            return;
        }

        int rewardExploit = campBattleData.getTotalRewardExploit(myCampRank);
        if(rewardExploit == 0)
        {
            LogUtils.debug("没有奖励可领取");
            playerController.sendWarn(WordFactory.ACTIVITY_CAMP_NO_REWARD);
            return;
        }

        BagInfo bagInfo = playerController.getPlayer().getExtInfo(BagInfo.class);
        bagInfo.addAsset(ConfigFactory.ASSET_EXPLOIT_KEY, rewardExploit);

        campBattleData.setGetRewarded(true);

        playerController.sendMsg(code, null);
    }

    private void battleRecord(PlayerController playerController, int code)
    {
        CampBattleData campBattleData = playerController.getPlayer().getCampBattleData();
        List<CampBattleBean> list = new ArrayList<>();
        list.addAll(campBattleData.getBattleList());
        Collections.reverse(list);

        SGChallengeProto.S2C_CampBattleRecord.Builder response = SGChallengeProto.S2C_CampBattleRecord.newBuilder();
        for(CampBattleBean campBattleBean : list)
        {
            response.addBattleRecord(campBattleBean.parse());
        }

        playerController.sendMsg(code, response.build().toByteArray());
    }



    private void campInit(PlayerController playerController, int code)
    {
        SGChallengeProto.S2C_ActivityCampInit.Builder response = SGChallengeProto.S2C_ActivityCampInit.newBuilder();

        CampBattleData campBattleData = playerController.getPlayer().getCampBattleData();

        if(!ActivityCampManager.getInstance().getIndex().equals(campBattleData.activityIndex))
        {
            campBattleData.clearApplyData();
            ActivityCampManager.getInstance().removePlayer(playerController.getObjectIndex());
        }

        BattleTemp battleTemp = GameServer.getInstance().getWorldManager().getSpriteBattleTemp(SGCommonProto.E_BATTLE_TYPE.BATTLE_TYPE_SPAN_CAMP_VALUE, playerController.getObjectIndex());
        int masterHP = 100, armyHP = 100;
        if(battleTemp != null)
        {
            masterHP = (int) ((double)battleTemp.getMaster().getHp() / battleTemp.getMaster().getMaxHp() * 100);
            int totalHP = 0, totalMaxHP = 0;
            for(SpriteTemp spriteTemp : battleTemp.getSoldierList())
            {
                totalHP += spriteTemp.getHp();
                totalMaxHP += spriteTemp.getMaxHp();
            }
            armyHP = (int) ((double)totalHP / totalMaxHP * 100);
        }

        response.setMasterHP(masterHP);
        response.setArmyHP(armyHP);
        response.setWinRate(campBattleData.getCurWinRate());
        response.setTotalCount(campBattleData.curBattleCount);
        response.setMaxContinueWin(campBattleData.curMaxContinueWin);
        response.setTotalExploit(campBattleData.curTotalExploit);

        BagInfo bagInfo = playerController.getPlayer().getExtInfo(BagInfo.class);
        response.setCurExploit(bagInfo.getAsset(ConfigFactory.ASSET_EXPLOIT_KEY));

        ActivityCampManager activityCampManager = ActivityCampManager.getInstance();
        response.setMaxExploitPlayer((activityCampManager.getMaxExploitPlayer().parse()));
        response.setMaxWinCountPlayer(activityCampManager.getMaxWinCountPlayer().parse());
        response.setMaxContinueWinPlayer(activityCampManager.getMaxContinueWinPlayer().parse());

        for(RankCamp rankCamp : activityCampManager.getRankCampList())
        {
            response.addRankCampList(rankCamp.parse());
        }

        response.setIsApplyed(campBattleData.applyCount>0&&campBattleData.reviveCount>=0);
        response.setReviveCount(campBattleData.reviveCount);


        int countdown = (int) ((ActivityCampManager.getInstance().getCampActivityIntervalNextStartTime() + 9000) / 1000);
        response.setCountdown(countdown);

        StableDataConfig stableData = DataFactory.getInstance().getGameObject(DataFactory.STABLE_DATA_KEY, E_StableDataType.CAMP_ACTIVITY_APPLY.getCode());
        GoodsData need = stableData.getGoodsData(campBattleData.applyCount);
        response.setApplyCharge(need.parse());

        playerController.sendMsg(code, response.build().toByteArray());
    }





    /**
    * 报名
    * @param playerController
    */
    private void applyCampActivity(PlayerController playerController)
    {
        if(ActivityCampManager.getInstance().getStatus() == E_ActivityCampStatus.CLEAR_ING)
        {
            LogUtils.debug("正在结算中，请稍候再试");
            playerController.sendWarn(WordFactory.ACTIVITY_CAMP_CLEAR_ING);
            return;
        }

        if(playerController.isBattling())
        {
            LogUtils.warn("战斗中不允许报名");
            playerController.sendWarn(WordFactory.ILLEGAL_ERROR);
            return;
        }

        StableDataConfig stableData = DataFactory.getInstance().getGameObject(DataFactory.STABLE_DATA_KEY, E_StableDataType.CAMP_ACTIVITY_APPLY.getCode());
        if(stableData == null || stableData.intValue <= 0)
        {
            LogUtils.error("阵营活动配置为空");
            playerController.sendWarn(WordFactory.PARAM_ERROR);
            return;
        }

        if(ServerManager.getInstance().getActivityServer() == null || ConfigFactory.gmSetting.isCloseCampActivity())
        {
            LogUtils.error("阵营战服务器没有开启!");
            playerController.sendWarn(WordFactory.ACTIVITY_SEVER_ERROR);
            return;
        }

        BagInfo bagInfo = playerController.getPlayer().getExtInfo(BagInfo.class);

        CampBattleData campBattleData = playerController.getPlayer().getCampBattleData();
        if(campBattleData.reviveCount >= 0)
        {
            LogUtils.error("已经报名过了");
            playerController.sendWarn(WordFactory.CAMP_ACTIVITY_APPLY_ED);
            return;
        }

        GoodsData need = stableData.getGoodsData(campBattleData.applyCount);
        if(need.value > 0)
        {
            if(bagInfo.getGoodsCount(need.type, need.id) < need.value)
            {
                if(SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_ASSETS_VALUE == need.type)
                {
                    LogUtils.debug("资源不足 -> " + need.id);
                    playerController.sendWarn(WordFactory.getWord(WordFactory.ASSET_NOT_ENOUGH, need.id));
                    return;
                }
                else if(SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_PROPS_VALUE == need.type)
                {
                    LogUtils.debug("道具不足 -> " + need.id);
                    playerController.sendWarn(WordFactory.getWord(WordFactory.GOODS_NOT_ENOUGH, need.id));
                    return;
                }
                else
                {
                    LogUtils.debug("其它不足 -> " + need.id);
                    playerController.sendWarn(WordFactory.getWord(WordFactory.PARAM_ERROR));
                    return;
                }
            }
        }

        ServerInfo activityServer = ServerManager.getInstance().getActivityServer();
        JSONObject checkResult = HttpJsonUtils.httpPost("http://" + activityServer.getHost() + ":" + activityServer.getHttpPort() + "/camp/checkApply", null);
        if(!checkResult.getString("code").equals(ReturnMessage.SUCCESS.getCode()))
        {
            playerController.sendWarn(checkResult.getString("message"));
            return;
        }

        if(need != null)
        {
            bagInfo.subGoods(need);
        }

        if(!ActivityCampManager.getInstance().getIndex().equals(campBattleData.activityIndex))
        {
            campBattleData.clearApplyData();
            ActivityCampManager.getInstance().removePlayer(playerController.getObjectIndex());
        }

        if(campBattleData.applyCount == 0 && ActivityCampManager.getInstance().getStatus() == E_ActivityCampStatus.RUN_ING)
        {
            campBattleData.clearReward();
        }

        campBattleData.apply(ActivityCampManager.getInstance().getIndex(), stableData.intValue, bagInfo.getCardData().getBattleCardList());

        ActivityCampManager.getInstance().applySuccess(playerController);

        ServerManager.getInstance().sendApplyActivity(playerController.getPlayer(), E_ApplyCampActivityType.DEFAULT);
    }





}
